package main

import (
	"context"
	"errors"
	"flag"
	"log"
	"os"
	"time"

	"github.com/olivere/elastic/v7"
)

/**
* Author: dinglin
* Date: 2021/8/31 10:32 上午
 */

func doSnapshot() {
	if config.fromHost == "" {
		log.Printf("from_host miss")
		flag.PrintDefaults()
		os.Exit(-1)
	}
	if config.repository == "" || config.fromIndex == "" || config.snapshotName == "" {
		log.Printf("repository or to_index miss")
		flag.PrintDefaults()
		os.Exit(-1)
	}
	from, err := NewEsClient(config.fromHost)
	if err != nil {
		os.Exit(-1)
	}
	err = snapshot(from, config.fromIndex, config.repository, config.snapshotName)
	if err != nil {
		os.Exit(-1)
	}
}

func snapshot(client *elastic.Client, index, repository, snapshotName string) error {
	log.Printf("start create snapshot[%s]: repository=%s, name=%s", index, repository, snapshotName)
	service := client.SnapshotCreate(repository, snapshotName)
	service.WaitForCompletion(false)
	service.BodyJson(map[string]interface{}{
		"indices":              index,
		"ignore_unavailable":   true,
		"include_global_state": false,
	})
	resp, err := service.Do(context.Background())
	if err != nil || resp.Accepted == nil || !*resp.Accepted {
		log.Printf("create snapshot[%s]: %v", index, err)
		return err
	}

	log.Printf("wait create compelete")
endLoop:
	for range time.Tick(time.Minute * 1) { //查询create snapshot 状态
		resp, err := client.SnapshotStatus().Repository(repository).Snapshot(snapshotName).Do(context.Background())
		if err != nil {
			log.Printf("get snapshot status failed %v, after 1m retry", err)
			continue
		}
		snapshot := resp.Snapshots[0]
		switch snapshot.State {
		case "SUCCESS":
			break endLoop
		case "IN_PROGRESS":
			log.Printf("in progress[%s] %v", index, print(snapshot.Stats))
		default:
			log.Printf("create snapshot[%s]: %v", index, snapshot.Indices)
			return errors.New("create snapshot failed")
		}
	}
	log.Printf("compelete create snapshot[%s] repository=%s, name=%s", index, repository, snapshotName)
	return nil
}
